package com.xxl.job.core.handler.impl;

import com.xxl.job.core.handler.IJobHandler;

import java.lang.reflect.Method;

/**
 * @author xuxueli 2019-12-11 21:12:18
 */
public class MethodJobHandler extends IJobHandler {

    private final Object target;
    private final Method method;
    private Method initMethod;
    private Method destroyMethod;
    private Method runStartMethod;
    private Method runEndMethod;
    public MethodJobHandler(Object target, Method method, Method initMethod, Method destroyMethod) {
        this.target = target;
        this.method = method;

        this.initMethod = initMethod;
        this.destroyMethod = destroyMethod;
        //获取每次运行的开始和结束方法
        Class<?> clazz = target.getClass();
        try {
            runStartMethod = clazz.getMethod("runStart");
            runStartMethod.setAccessible(true);
        } catch (NoSuchMethodException ignored) {
        }
        try {
            runEndMethod = clazz.getMethod("runEnd",Throwable.class);
            runEndMethod.setAccessible(true);
        } catch (NoSuchMethodException ignored) {
        }
    }
    @Override
    public void execute() throws Exception {
        Class<?>[] paramTypes = method.getParameterTypes();
        try {
            if(runStartMethod !=null){
                runStartMethod.invoke(target);
            }
            if (paramTypes.length > 0) {
                method.invoke(target, new Object[paramTypes.length]);       // method-param can not be primitive-types
            } else {
                method.invoke(target);
            }
            if(runEndMethod!=null){
                runEndMethod.invoke(target,new Object[]{null});
            }
        }catch (Throwable t){
            if(runEndMethod!=null){
                runEndMethod.invoke(target,t);
            }
            throw t;
        }
    }

    @Override
    public void init() throws Exception {
        if(initMethod != null) {
            initMethod.invoke(target);
        }
    }

    @Override
    public void destroy() throws Exception {
        if(destroyMethod != null) {
            destroyMethod.invoke(target);
        }
    }

    @Override
    public String toString() {
        return super.toString()+"["+ target.getClass() + "#" + method.getName() +"]";
    }
}
